﻿/**************************************************************
 *
 * 唯一标识：02ba8fb0-777d-481f-af91-72656c4d6f46
 * 命名空间：Sgr.UPMS.Application.Commands.Departments
 * 创建时间：2023/8/27 20:05:34
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：删除部门命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Departments;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Departments
{
    /// <summary>
    /// 删除部门命令处理器
    /// </summary>
    public class DeleteDepartmentCommandHandle : IRequestHandler<DeleteDepartmentCommand, CommandResult<bool>>
    {
        private readonly IDepartmentManage _departmentManage;
        private readonly IDepartmentRepository _departmentRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository">部门仓储</param>
        /// <param name="departmentManage">部门管理器</param>
        public DeleteDepartmentCommandHandle(IDepartmentRepository departmentRepository,
          IDepartmentManage departmentManage)
        {
            _departmentRepository = departmentRepository;
            _departmentManage = departmentManage;
        }

        /// <summary>
        /// 处理删除部门命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(DeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            // 查找部门实体
            var entity = await _departmentRepository.GetAsync(request.DepartmentId, cancellationToken);

            // 如果找不到部门，返回NotFound结果
            if (entity == null)
                return CommandResult.NotFound<bool>("未找到指定的部门");
            // 调用领域服务删除部门节点（如果IsCascade为true，则会级联删除子部门）
            bool result = await _departmentManage.RemoveNodeAsync(entity, request.IsCascade, cancellationToken);

            // 验证删除结果
            if (!result)
                return CommandResult.Invalid<bool>("删除部门失败，可能存在关联数据");

            // 返回成功结果
            return CommandResult.Success(true, "部门删除成功");
        }
    }
}